import { getProdUnionResultApi, prodClickCountApi } from "src/api/prod";
import { isWeChat } from "src/utils/lib";
import { useOpenLink } from "../openlink/OpenLink";
import { ProdJumpDialogInstance } from '../../components/ProdJump'
import { nextTick } from "vue";
import { getRouter } from "src/router";
type PrivacyItem = {
  name: string,
  url: string,
  key: string
}
export type ProdItem = {
  detailUrl: string; // 产品跳转页面
  maxAmount: string;
  productId: string;
  productLabel: string;
  productLogo: string;
  productName: string;
  productTitle: string;
  rateAmountInfo: string;
  unionFlag: boolean; //false 直接跳转 detailUrl; true 先判断detailUrl是否有值，有值直接跳转，没有的话。请求【产品联登结果】结果，获取跳转地址
  downloadFlag: number; //是否在下载应用；1 下载；0 不下载
  jumpStatus: number; // 1 跳 0 不跳
  backgroundLogo: string;
  privacy: PrivacyItem[];
  speed: string;
  loanTime: string;
};

export type ResType = {
  dataList: ProdItem[];
};
const openDialog = (url: string, wechatJumpRef?: ProdJumpDialogInstance) => {
  if (wechatJumpRef) {
    nextTick(() => {
      wechatJumpRef.show({
        url
      })
    })
  }
}

export const gotoProd = async (prod: ProdItem, token?: string, wechatJumpRef?: ProdJumpDialogInstance, isShop: boolean = false) => {
  await prodClickCountApi({ productId: prod.productId, token });
  console.log(123);
  sessionStorage.setItem("jumpProdImg", prod.productLogo)
  sessionStorage.setItem("jumpProdName", prod.productName)
  // return openDialog(prod.detailUrl, wechatJumpRef)
  if (prod.unionFlag) {
    if (!prod.detailUrl) {
      
      const res = await getProdUnionResultApi({ productId: prod.productId, token });

      if (!!Number(prod.jumpStatus) && isWeChat()) {
        return openDialog(res.data.detailUrl, wechatJumpRef)
        // return getRouter().push({ path: '/prodJump', query: { ...getRouter().currentRoute.value.query, jumpUrl: encodeURIComponent(res.data.detailUrl) } })
      }
      if(res.data.detailUrl){
        if(isShop){
          location.href = res.data.detailUrl
          return
        }
        useOpenLink().goTo(res.data.detailUrl)
      }else{
        console.log(res.data.detailUrl)
        getRouter().push({ path: '/home', query: { ...getRouter().currentRoute.value.query, reload: Date.now()}})
        // router.replace({ path: '/home', query: route.query });
      }
      return;
    }
  }

  if (prod.detailUrl) {
    if (!!Number(prod.jumpStatus) && isWeChat()) {
      return openDialog(prod.detailUrl, wechatJumpRef)
      // return getRouter().push({ path: '/prodJump', query: { ...getRouter().currentRoute.value.query, jumpUrl: encodeURIComponent(prod.detailUrl) } })
    }
    if(isShop){
      location.href = prod.detailUrl
      return
    }
    useOpenLink().goTo(prod.detailUrl)
  }
};


